<template>
  <div>
    <!--搜索查询-->
    <el-row>
      <el-col :span="6">&nbsp;</el-col>
      <el-col :span="4"
      >
        <el-input
            v-model="searchForm.loginName"
            size="mini"
            clearable
            placeholder="请输登录名称"
        ></el-input
        >
      </el-col>
      <el-col :span="4"
      >
        <el-input
            v-model="searchForm.phonenumber"
            size="mini"
            clearable
            placeholder="请输用户名"
        ></el-input
        >
      </el-col>
      <el-col :span="2"
      >
        <el-button
            type="primary"
            size="mini"
            @click="search()"
            icon="el-icon-search"
            v-has="'user:query'"
        >搜索
        </el-button
        >
      </el-col
      >
      <el-col :span="2"
      >
        <el-button
            type="primary"
            size="mini"
            @click="handlerAdd(),this.form=''"
            icon="el-icon-circle-plus"
            v-has="'user:add'"
        >添加
        </el-button
        >
      </el-col
      >
      <el-col :span="2"
      >
        <el-button
            type="primary"
            size="mini"
            v-has="'user:query'"
            @click="flush()"
            icon="el-icon-refresh"
        >刷新
        </el-button
        >
      </el-col
      >
    </el-row>


    <!--        数据表格-->
    <el-row>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column label="用户头像">
          <template slot-scope="scope">
            <el-image
                style="width: 60px; height: 60px"
                :src="scope.row.avatar"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column
            prop="loginName"
            label="姓名"
            align="center"
            width="100"
        >
        </el-table-column>
        <el-table-column
            prop="userName"
            align="center"
            label="用户名"
            width="100"
        >
        </el-table-column>
        <el-table-column prop="email" width="280" align="center" label="邮箱">
        </el-table-column>

        <el-table-column
            prop="phonenumber"
            label="电话号码"
            align="center"
            width="180"
        >
        </el-table-column>
        <el-table-column prop="sex" :formatter="sexFormat" label="性别">
        </el-table-column>
        <el-table-column prop="status" :formatter="zhFormat" label="账号状态">
        </el-table-column>
        <el-table-column width="150" label="用户状态">
          <template slot-scope="scope">
            <el-switch
                v-model="scope.row.status"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-value="0"
                inactive-value="1"
                active-text="启用"
                inactive-text="禁用"
                @change="handleChangeStatus(scope.$index, scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>


        <!-- <el-table-column prop="delFlag" :formatter="delFormat" label="删除状态">
        </el-table-column> -->
        <!--                右侧操作栏-->
        <el-table-column label="操作" fixed="right" width="250" align="center">
          <template slot-scope="scope">
            <el-button
                size="mini"
                type="primary"
                v-has="'user:impower'"
                @click="(rolesVisible=true),addUserRole(scope.$index, scope.row),getUserRole(scope.$index, scope.row)"
            >授予角色
            </el-button
            >
            <el-button
                size="mini"
                v-has="'user:update'"
                @click="handleEdit(scope.$index, scope.row)"
            >编辑
            </el-button
            >
            <el-button
                size="mini"
                type="danger"
                v-has="'user:delete'"
                @click="handleDelete(scope.$index,scope.row)"
            >删除
            </el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-row>


    <el-row>
      <!--分页插件-->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[2, 3, 5, 10, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      >
      </el-pagination>
    </el-row>


          <!--角色授权弹出框-->
      <el-dialog title="角色列表" :visible.sync="rolesVisible">
        <el-form :model="role"  ref="form">
          <el-form-item
              label="选择角色"
              prop="deptId"
              :label-width="formLabelWidth"
          >
            <template>
              <div style="margin: 15px 0;"></div>
              <el-checkbox-group v-model="checkedRoles" @change="handleCheckedCitiesChange">
                <el-checkbox v-for="role in roleData" :label="role.roleId" :key="role">{{role.roleName}}</el-checkbox>
              </el-checkbox-group>
            </template>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitRole(),(rolesVisible=false)">确 定</el-button>
        </div>
      </el-dialog>



    <!--用户添加/更新对话框-->
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item
            label="账号名称"
            prop="loginName"
            :label-width="formLabelWidth"
        >
          <el-input v-model="form.loginName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
            label="用户昵称"
            prop="userName"
            :label-width="formLabelWidth"
        >
          <el-input v-model="form.userName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
            label="密码"
            prop="password"
            :label-width="formLabelWidth"
            v-if="this.title == '用户更新' ? false : true"
        >
          <el-input
              v-model="form.password"
              autocomplete="off"
              show-password
          ></el-input>
        </el-form-item>
        <el-form-item
            label="用户邮箱"
            prop="email"
            :label-width="formLabelWidth"
        >
          <el-input v-model="form.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
            label="手机号码"
            prop="phonenumber"
            :label-width="formLabelWidth"
        >
          <el-input v-model="form.phonenumber" autocomplete="off"></el-input>
        </el-form-item>
        <template>
          性别
          <el-radio v-model="form.sex" label="0">男</el-radio>
          <el-radio v-model="form.sex" label="1">女</el-radio>
        </template>

        <el-form-item
            label="选择部门"
            prop="deptId"
            :label-width="formLabelWidth"
        >
          <el-select v-model="form.deptId" placeholder="请选择">
            <el-option
                v-for="item in optionsA"
                :key="item.deptno"
                :label="item.dname"
                :value="item.deptno"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-upload
            class="avatar-uploader"
            action="http://localhost:10066/user/upload"
            :show-file-list="true"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>


<script>
export default {
  data() {
    return {
      value: true,
      role:{},
      roleData: {
        roleId:[],
        roleName:[]
      },
      optionsA: [],                       // 部门
      optionsB: {
        dictValue: [0,1],
        dictLabel: ["男","女"]
      },                       // 性别Ａ
      tableData: [],                      // 数据表格
      imageUrl: "",                         // 添加头像
      currentPage: 1,                     // 页码 第几页
      pageSize: 5,                        // 每页显示数量
      total: 100,                         // 总条数
      searchForm: {loginName: "", phonenumber: "", email: "", userName: ""}, // 模糊搜索form表单
      title: "用户添加",                    // 添加修改时的默认标题
      dialogFormVisible: false,            // 添加修改的弹出框是否显示  默认是不显示
      form: {},                            // 添加修改的form表单对象
      formLabelWidth: "120px",             // 添加修改的form表单输入框的宽度
      condition: "",
      rolesVisible: false,                 // 不显示角色授权列表对话框
      isIndeterminate: true,
      checkAll: false,                     // 角色授权是否全选
      checkedRoles: [],                    // 默认选中项
      roleList: [],                        // 有效角色集合
      roleIds: "",                         // 定义选中的所有角色ID集合
      userId: 0,                           // 定义用户ID
      rules: {                             // 用户添加更新内容要求
        form: {},
        loginName: [
          {required: true, message: "请输入账号名称（汉）", trigger: "blur"},
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        userName: [
          {required: true, message: "请输入用户昵称（英）", trigger: "blur"},
          {
            min: 3,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          {required: true, message: "请输入密码", trigger: "blur"},
          {required: true, message: "密码不能为空", trigger: "blur"},
        ],
        email: [
            {required: true, message: "请输入邮箱", trigger: "blur"},
            {
                pattern:
                    /^([0-9A-Za-z\-_\.]+)@([0-9a-z]+\.[a-z]{2,3}(\.[a-z]{2})?)$/g,
                message: "请输入正确的邮箱",
                trigger: "blur",
            },
        ],
        phonenumber: [
            {required: true, message: "请输入手机号", trigger: "blur"}, // 这个只能验证手机号 // { pattern:/^0{0,1}(13[0-9]|15[7-9]|153|156|18[7-9])[0-9]{8}$/, message: "请输入合法手机号", trigger: "blur" }
            {
                pattern: /^((0\d{2,3}-\d{7,8})|(1[356789]\d{9}))$/,
                message: "请输入合法手机号/电话号",
                trigger: "blur",
            },
        ],
        sex: [{required: true, message: "请选择性别", trigger: "change"}],
        deptId: [{required: true, message: "请选择部门", trigger: "change"}],
      },
    };
  },


  created() {
    //初始化方法 类似于jquery  $({})
    this.loadData();
    var _this = this;
    _this.$http
        .post("/dept/queryByPage", {
          pageNo: this.currentPage,
          pageSize: 100,
          data: {},
        })
        .then(function (response) {
          console.log(JSON.stringify(response));
          if (response.data.code == 200) {
            _this.optionsA=response.data.data.list
          }
        })
        .catch(function (error) {
          //错误的处理
          // handle error
          console.log(error);
        })
        .then(function () {
          //总执行 最终处理      类似java  异常处理的finally
          // always executed
        });

    // _this.$http
    //     .post("/dictData/queryByPage", {
    //       pageNo: this.currentPage,
    //       pageSize: 100,
    //       data: {
    //         dictType: "sys_user_sex",
    //         status: "0",
    //       },
    //     })
    //     .then(function (response) {
    //       console.log(JSON.stringify(response));
    //       if (response.data.code == 200) {
    //         _this.optionsB = response.data.data.list;
    //         _this.total = response.data.data.total;
    //       }
    //     })
    //     .catch(function (error) {
    //       //错误的处理
    //       // handle error
    //       console.log(error);
    //     })
    //     .then(function () {
    //       //总执行 最终处理      类似java  异常处理的finally
    //       // always executed
    //     });

//查询所有有效角色，为roleList赋值
    var _this = this;
    this.$http
        .get("/role/queryAll")
        .then(function (response) {
          if (response.data.code == 200) {
            _this.roleData = response.data.data;
          }
        })
        .catch(function (error) {
          console.log(error);
          _this.$message.error("你错了。。。");
        });
  },


  //所有函数
  methods: {
    getUserRole(index,row){
      var _this = this;
      //复制 $http官网代码
      // var token  = localStorage.getItem("token");
      _this.$http
          .get("/user/getUserRole?userId="+_this.userId)
          .then(function (response) {
            if (response.data.code == 200) {
              _this.checkedRoles = response.data.data;
            }
          })
          .catch(function (error) {
            console.log(error);
          });
    },
    addUserRole(index,row){
      var _this = this;
      _this.userId=row.userId
    },
    //加载数据
    loadData() {
      var _this = this;
      //复制 $http官网代码
      // var token  = localStorage.getItem("token");
      _this.$http
          .post("/user/queryByPage", {
            pageNo: this.currentPage,
            pageSize: this.pageSize,
            data: {
              loginName: this.searchForm.loginName,
              phonenumber: this.searchForm.phonenumber,
              email: this.searchForm.email,
              userName: this.searchForm.userName,
            },
          })
          .then(function (response) {
            if (response.data.code == 200) {
              _this.tableData = response.data.data.list;
              _this.total = response.data.data.total;
            }
          })
          .catch(function (error) {
            console.log(error);
          });
    },
    //处理更新
    handleEdit(index, row) {
      var _this = this;
      //row  当前行数据 如果是第一行  row = {deptId:1,deptName:'管理部'把一行数据赋值给form赋值,description:'店长的事',status:1}
      console.log(index, row);
      //显示对话框
      _this.dialogFormVisible = true;
      //指定对话框标题
      _this.title = "用户更新";
      //把一行数据赋值给form赋值
      _this.form = row;
      //把数字1变为字符串1
      _this.form.status = row.status + "";
      _this.imgUrl = row.avatar;
    },
    //处理添加
    handlerAdd() {
      this.imgUrl = "";
      //显示对话框
      this.dialogFormVisible = true;
      //指定对话框标题
      this.title = "用户添加";
      //让form表单重新赋空值
      this.form = {};
    },
    submitRole(){
      var _this = this;
      //复制 $http官网代码
      // var token  = localStorage.getItem("token");
      console.log(_this.checkedRoles)
      _this.$http
          .get("/user/addRole?updateBy="+_this.checkedRoles+"&userId="+_this.userId)
          .then(function (response) {
            _this.loadData()
          })
          .catch(function (error) {
            console.log(error);
          });
    },
    //提交表单
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var url = "";
          //让_this等于当前vue对象
          var _this = this;

          if (this.title == "用户添加") {
            _this.form.createBy = localStorage.getItem("userName")
            _this.form.avatar=_this.imageUrl
            url = "/user/add";
            _this.$http
                .post(url, this.form,) //指定请求的url及参数  get
                .then(function (response) {
                  //正确返回对象的处理
                  // handle success
                  console.log(response);
                  //JSON.stringify   把json转换为json字符串，方便查看
                  console.log(JSON.stringify(response));
                  //直接使用this 会指 $http对象  错误
                  // this.tableData
                  //判断返回值是否正确
                  if (response.data.code == 200) {
                    //关闭弹框
                    _this.dialogFormVisible = false;
                    //提示添加成功
                    _this.$message({
                      message: "恭喜你，这是一条成功消息",
                      type: "success",
                    });
                    //重新加载数据
                    _this.loadData();
                  } else {
                    //错误提示信息
                    _this.$message.error("错了哦，这是一条错误消息");
                  }
                })
                .catch(function (error) {
                  //错误的处理
                  // handle error
                  console.log(error);
                });
          }

          if (this.title == "用户更新") {
            _this.form.updateBy = localStorage.getItem("userName")
            url = "/user/edit";
            // alert(111);
            //赋值 $http官网代码  this.form =form:{deptName:'',description:'',status:1}
            _this.$http
                .put(url, this.form) //指定请求的url及参数  get
                .then(function (response) {
                  //正确返回对象的处理
                  // handle success
                  console.log(response);
                  //JSON.stringify   把json转换为json字符串，方便查看
                  console.log(JSON.stringify(response));
                  //直接使用this 会指 $http对象  错误
                  // this.tableData
                  //判断返回值是否正确
                  if (response.data.code == 200) {
                    //关闭弹框
                    _this.dialogFormVisible = false;
                    //提示添加成功
                    _this.$message({
                      message: "恭喜你，这是一条成功消息",
                      type: "success",
                    });
                    //重新加载数据
                    _this.loadData();
                  } else {
                    //错误提示信息
                    _this.$message.error("错了哦，这是一条错误消息");
                  }
                })
                .catch(function (error) {
                  //错误的处理
                  // handle error
                  console.log(error);
                });
          }

        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    //格式化性别方法
    sexFormat(row, column, cellValue, index) {
      //row当前行数据
      //column 列名称
      //cellValue 列的值
      //index 下标
      //alert(cellValue);
      return cellValue == 0 ? "男" : cellValue == 1 ? "女" : "未知";
      /**  if(cellValue==0){
                    return '男';
                }else if(cellValue==1){
                    return '女';
                }
       return '未知';
       */
    },

    zhFormat(row, column, cellValue, index) {
      //row当前行数据
      //column 列名称
      //cellValue 列的值
      //index 下标
      //alert(cellValue);
      return cellValue == 0 ? "正常" : "异常";
    },

    delFormat(row, column, cellValue, index) {
      //row当前行数据
      //column 列名称
      //cellValue 列的值
      //index 下标
      //alert(cellValue);
      return cellValue == 0 ? "存在" : "消失了";
    },
    handleCheckAllChange(val) {
      this.checkedCities = val ? cityOptions : [];
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.cities.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
    },

    //处理每页数量发生变化
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      //让每页数量发生变化
      this.pageSize = val;
      //重载数据
      this.loadData();
    },

    //处理当前页变化
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      //让每页数量发生变化
      this.currentPage = val;
      //重载数据
      this.loadData();
    },
    //查询
    search() {
      this.loadData();
    },
    //刷新
    flush() {
      location.reload();
    },


    //上传前图片类型和大小判断
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      console.log(file)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    }
  },
  //取消按钮
  dialogFormVisiblExit() {
    this.imgUrl = "";
    this.form = "";
    this.dialogFormVisibleAdd = false;
  },
  //处理逻辑删除
  handleDelete(index, row) {
    console.log(index, row);
    //确认框提示
    this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
        .then(() => {
          //让_this等于当前vue对象
          var _this = this;
          // alert(111);
          //赋值 $http官网代码  this.form =form:{deptName:'',description:'',status:1}
          _this.$http
              .delete("/user/deleteById?userId=" + row.userId) //指定请求的url及参数  get
              .then(function (response) {
                //正确返回对象的处理
                // handle success
                console.log(response);
                //JSON.stringify   把json转换为json字符串，方便查看
                console.log(JSON.stringify(response));
                //直接使用this 会指 $http对象  错误
                // this.tableData
                //判断返回值是否正确
                if (response.data.code == 200) {
                  //提示添加成功
                  _this.$message({
                    message: "恭喜你，这是一条成功消息",
                    type: "success",
                  });
                  //重新加载数据
                  _this.loadData();
                } else {
                  //错误提示信息
                  _this.$message.error("错了哦，这是一条错误消息");
                }
              })
              .catch(function (error) {
                //错误的处理
                // handle error
                console.log(error);
              });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
  },

  //处理是否全选中方法
  handleCheckAllChange(val) {
    // alert(val);
    if (val) {
      // alert(JSON.stringify(this.roleList));
      for (var i = 0; i < this.roleList.length; i++) {
        //alert(this.roleList[i].roleId);
        var tempRI = this.roleList[i].roleId;
        this.checkedRoles.push(tempRI);
        this.roleIds += tempRI + ",";
      }
      //去掉最后一个逗号
      this.roleIds = this.roleIds.substr(0, this.roleIds.length - 1);
      // alert(this.roleIds);
    } else {
      this.checkedRoles = [];
      this.roleIds = "";
    }
  },
  //处理重新选择结果
  handleCheckedRolesChange(val) {
    //alert(val);
    //把选中的值赋值给roleIds
    this.roleIds = val;
  },

 //修改用户状态（禁用/启用）
  handleChangeStatus(index, row) {
    var _this = this; //复制 $http官网代码 // var token  = localStorage.getItem("token");
    alert(JSON.stringify(row));
    _this.$http
        .post("/user/edit", row)
        .then(function (response) {
          if (response.data.code == 200) {
            //alert("操作成功");
            _this.loadData;
          }
        })
        .catch(function (error) {
          console.log(error);

        });
  },
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 178px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

</style>
